package com.elbis.business.util;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Paginator<T> implements Serializable {

	private static final long serialVersionUID = 5287471424034456919L;

	private static final int DEFAULT_RECORDS_NUMBER = 10;

	private static final int DEFAULT_PAGE_INDEX = 1;

	private int records;

	private int recordsTotal;

	private int pageIndex;

	private int pages;

	private List<T> origModel;

	private List<T> model;

	public Paginator(List<T> model) {
		if (model == null) {
			recordsTotal = 0;
			origModel = new ArrayList<T>();
		} else {
			recordsTotal = model.size();
			origModel = model;
		}
		records = DEFAULT_RECORDS_NUMBER;
		pageIndex = DEFAULT_PAGE_INDEX;

		if (records > 0) {
			pages = records <= 0 ? 1 : recordsTotal / records;

			if (recordsTotal % records > 0) {
				pages++;
			}

			if (pages == 0) {
				pages = 1;
			}
		} else {
			records = 1;
			pages = 1;
		}

		updateModel();
	}

	public void updateModel() {
		int fromIndex = getFirst();
		int toIndex = getFirst() + records;
		if (toIndex > recordsTotal) {
			toIndex = recordsTotal;
		}
		model = origModel.subList(fromIndex, toIndex);
	}

	public String next() {
		if (this.pageIndex < pages) {
			this.pageIndex++;
		}
		updateModel();
		return null;
	}

	public String prev() {
		if (this.pageIndex > 1) {
			this.pageIndex--;
		}
		updateModel();
		return null;
	}

	public int getRecords() {
		return records;
	}

	public int getRecordsTotal() {
		return recordsTotal;
	}

	public int getPageIndex() {
		return pageIndex;
	}

	public int getPages() {
		return pages;
	}

	public int getFirst() {
		return (pageIndex * records) - records;
	}

	public List<?> getModel() {
		return model;
	}

	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}

}
